package com.zhiwang.xiaoqu.widget

import android.content.Context
import android.graphics.drawable.LevelListDrawable
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.zhiwang.xiaoqu.R

/**
 * 为了叠加在一起，继承 FrameLayout
 */
class WithDrawSelector : FrameLayout {

    val TAG = "WithDrawSelector"

    lateinit var aliTextView: TextView

    lateinit var weinxinTextView: TextView

    var selectedIndex = 0

    var prevIndex = 0

    var onSelectChangeListener: OnSelectChangeListener? = null

    interface OnSelectChangeListener {
        fun onSelectChange(index: Int)
    }


    var onItemClickListener = OnClickListener { v ->
        if (v == aliTextView) {
            prevIndex = selectedIndex
            selectedIndex = 0
        } else {
            prevIndex = selectedIndex
            selectedIndex = 1
        }

        if (prevIndex != selectedIndex) {
            onSelectChangeListener?.onSelectChange(selectedIndex)
            requestLayout()
        }
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        aliTextView = findViewWithTag("alipay")
        weinxinTextView = findViewWithTag("weixin")
        measureChildWithMargins(aliTextView, widthMeasureSpec, 0, heightMeasureSpec, 0)
        measureChildWithMargins(weinxinTextView, widthMeasureSpec, 0, heightMeasureSpec, 0)

        val w = aliTextView.measuredWidth + weinxinTextView.measuredWidth - 40
        val h = Math.max(aliTextView.measuredHeight, weinxinTextView.measuredHeight)
        setMeasuredDimension(w, h)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {

        aliTextView.layout(0, 0, aliTextView.measuredWidth, measuredHeight)

        weinxinTextView.layout(measuredWidth - weinxinTextView.measuredWidth - 40, 0, measuredWidth, measuredHeight)

        (aliTextView.background as LevelListDrawable).level = 1 - selectedIndex
        (weinxinTextView.background as LevelListDrawable).level = selectedIndex

        aliTextView.setTextColor(
            ContextCompat.getColor(
                context,
                if (selectedIndex == 0) R.color.colorPrimary else R.color.colorWhite1
            )
        )

        weinxinTextView.setTextColor(
            ContextCompat.getColor(
                context,
                if (selectedIndex == 1) R.color.colorPrimary else R.color.colorWhite1
            )
        )

        aliTextView.setOnClickListener(onItemClickListener)
        weinxinTextView.setOnClickListener(onItemClickListener)
    }

    override fun getChildDrawingOrder(childCount: Int, i: Int): Int {

        return if (selectedIndex == 0) i
        else 1 - i

    }
}